/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q2502.java
 * @Author : WangRuoyu
 * @Date 2022/12/17 17:09
 */

package leetcode;

import java.util.Arrays;

public class Q2502 {
    int[] array;

    //    public Allocator(int n){
    public Q2502(int n) {
        array = new int[n];
    }

    public int allocate(int size, int mID) {
        int index = -1;
        int tmp = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 0) {
                if (tmp == 0) {
                    index = i;
                }
                tmp++;
                if (tmp >= size) {
                    break;
                }
            } else {
                tmp = 0;
            }
        }
        if (tmp >= size) {
            for (int i = index; i < index + tmp; i++) {
                array[i] = mID;
            }
            return index;
        } else {
            return -1;
        }
    }

    public int free(int mID) {
        int res = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == mID) {
                array[i] = 0;
                res++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int n = 10;
        int size = 2;
        int mID = 3;
        Q2502 obj = new Q2502(n);
        int param_1 = obj.allocate(size, mID);
        int param_2 = obj.free(mID);
        System.out.println(Arrays.toString(obj.array));
        System.out.println(param_1);
        System.out.println(param_2);
    }
}